package com.dengyuanke.wx.config;

import com.dengyuanke.utils.PropertiesUtil;
import com.dengyuanke.wx.common.Context;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

import java.util.Properties;

/**
 * Created by dengyuanke on 2017/11/2.
 */
public class WxMenuConfig {

    /**
     * 定义菜单结构
     *
     * @return
     */
    protected static WxMenu getMenu() {
        MainConfig mainConfig = new MainConfig();
        WxMpService wxMpService = mainConfig.wxMpService();

        WxMenu menu = new WxMenu();
        WxMenuButton button1 = new WxMenuButton();
        button1.setType(WxConsts.BUTTON_VIEW);
        button1.setName("进入首页");
        button1.setUrl(wxMpService.oauth2buildAuthorizationUrl(Context.OAUTH2USERINFO_URL, "snsapi_base", ""));
        menu.getButtons().add(button1);
        return menu;
    }

    public static class MainConfig {
        private String appId;
        private String appSecret;
        private String token;
        private String aesKey;

        /**
         * 为了生成自定义菜单使用的构造函数
         *
         */
        protected MainConfig() {
            Properties properties = new PropertiesUtil("wx.properties").getProperties();
            String appId = properties.getProperty("appId");
            String appSecret = properties.getProperty("appSecret");
            String token = properties.getProperty("token");
            String aesKey = properties.getProperty("aesKey");
            this.appId = appId;
            this.appSecret = appSecret;
            this.token = token;
            this.aesKey =aesKey;
        }

        public WxMpConfigStorage wxMpConfigStorage() {
            WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();
            configStorage.setAppId(this.appId);
            configStorage.setSecret(this.appSecret);
            configStorage.setToken(this.token);
            configStorage.setAesKey(this.aesKey);
            return configStorage;
        }

        public WxMpService wxMpService() {
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
            return wxMpService;
        }
    }

    /**
     * 运行此main函数即可生成公众号自定义菜单
     *
     * @param args
     */
    public static void main(String[] args) {
        MainConfig mainConfig = new MainConfig();
        WxMpService wxMpService = mainConfig.wxMpService();
        try {
            wxMpService.getMenuService().menuCreate(getMenu());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
